//
//  UnloginPersonalHomePageVC.m
//  PrivateSteward
//
//  Created by lanou3g on 16/3/24.
//  Copyright © 2016年 闫贺晨. All rights reserved.
//

#import "UnloginPersonalHomePageVC.h"
#import "PersonalHomepageCell.h"
#import "AboutUsViewController.h"
#import "LoginVC.h"
#import "PersonalSettingVC.h"
#import "SecurityHelperVC.h"
#import "CashbookVC.h"
#import <LocalAuthentication/LocalAuthentication.h>
@interface UnloginPersonalHomePageVC ()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,strong)LoginVC *loginvc;
@property(nonatomic,strong)PersonalSettingVC *persnalSettingvc;
@property(nonatomic,strong)SecurityHelperVC *secrityVC;
@property(nonatomic,strong)CashbookVC *cashbookVC;
@property(nonatomic,strong)NSString *securityPwd;

@end


@implementation UnloginPersonalHomePageVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.isLogin = NO;
    [self initView];
    self.persnalSettingvc = [[PersonalSettingVC alloc]init];
    [self.detailTableView registerClass:[PersonalHomepageCell class] forCellReuseIdentifier:@"personal"];
    [self.unLoginButton addTarget:self action:@selector(unLoginAction:) forControlEvents:UIControlEventTouchUpInside];
    self.loginvc = [[LoginVC alloc]init];
//    //添加是否注册通知,改变isLogin的值
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(didlogin) name:@"didlogin" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(unlogin) name:@"unlogin" object:nil];
}

//成功登陆事件
-(void)didlogin
{
    self.myImageView.userInteractionEnabled = YES;
    self.isLogin = YES;
    self.switchAccountButton.hidden = NO;
    //登陆成功后获取默认头像
    AVQuery *query = [AVQuery queryWithClassName:@"UserClass"];
    [query whereKey:@"phoneNumber" equalTo:[AVUser currentUser].username];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (objects.count > 0 ) {
            self.myImageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:objects[0][@"localData"][@"userImageUrl"]]]];
            NSLog(@"url   %@",objects[0][@"localData"][@"userImageUrl"]);
            [self.unLoginButton setTitle:objects[0][@"localData"][@"username"] forState:UIControlStateNormal];
        }
    }];
    //给头像添加点击事件
    UITapGestureRecognizer *type = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(TapAction:)];
    [self.myImageView  addGestureRecognizer:type];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"didlogin" object:nil];

}
-(void)unlogin
{
    self.isLogin = NO;
    self.switchAccountButton.hidden = YES;
}

-(void)TapAction:(UITapGestureRecognizer *)sender
{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(didlogin) name:@"didlogin" object:nil];
    self.persnalSettingvc.isReSet = NO;
    [self.navigationController pushViewController:self.persnalSettingvc animated:YES];
}
-(void)initView
{
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.hidden = YES;
    self.myView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 220)];
    self.myView.backgroundColor = [UIColor colorWithRed:124/255.0 green:213/255.0 blue:254/255.0 alpha:1];
    [self.view addSubview:_myView];
    
    self.myImageView = [[UIImageView alloc]initWithFrame:CGRectMake(20, CGRectGetMaxY(self.myView.bounds) - 40, 90, 90)];
    self.myImageView.image = [UIImage imageNamed:@"default_account_userphoto_default@2x"];
    //inmageview的用户交互
    self.myImageView.userInteractionEnabled = YES;
    self.myImageView.layer.cornerRadius = 45;
    [self.myView addSubview:_myImageView];
    
    
    self.unLoginButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.unLoginButton.frame = CGRectMake(150, CGRectGetMaxY(self.myView.bounds) , 200, 40);
    self.unLoginButton.tintColor = [UIColor whiteColor];
    self.unLoginButton.titleLabel.textAlignment = NSTextAlignmentLeft;
    [self.unLoginButton setTitle:@"未登录" forState:UIControlStateNormal];
    self.unLoginButton.titleLabel.font = [UIFont systemFontOfSize:16];
    self.unLoginButton.tintColor = [UIColor grayColor];
    
    [self.view addSubview:self.unLoginButton];
    
    self.detailTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.myImageView.frame), CGRectGetWidth(self.view.frame), self.view.frame.size.height)];
    [self.view addSubview:self.detailTableView];
    self.detailTableView.delegate = self;
    self.detailTableView.dataSource = self;
    self.switchAccountButton = [UIButton buttonWithType:UIButtonTypeSystem];
    
    self.switchAccountButton.frame = CGRectMake(CGRectGetMaxX(self.myView.frame) - 120,CGRectGetMinY(self.myView.frame) + 20, 120, 40);
    self.switchAccountButton.tintColor = [UIColor grayColor];
    self.switchAccountButton.titleLabel.font = [UIFont systemFontOfSize:16];
    //self.switchAccountButton.backgroundColor = [UIColor blueColor];
    [self.myView addSubview:self.switchAccountButton];
    [self.switchAccountButton setTitle:@"切换账号" forState:UIControlStateNormal];
    
    [self.switchAccountButton addTarget:self action:@selector(switchAccount) forControlEvents:UIControlEventTouchUpInside];
    
    
    
}

-(void)switchAccount
{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(didlogin) name:@"didlogin" object:nil];
    [self.navigationController pushViewController:self.loginvc animated:YES];
}

-(void)unLoginAction:(UIButton *)unloginButton
{
    if (self.isLogin == NO) {
        [self.navigationController pushViewController:self.loginvc animated:YES];
    }
    else
    {
       [self alertAction:@"确认退出" message:@"确认要退出当前账号吗?"];
      
    }
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 6;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    PersonalHomepageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"personal"];
    if (cell == nil) {
        cell = [[PersonalHomepageCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"personal"];
    }
    switch (indexPath.row) {
        case 0:
            cell.guideImageView.image = [UIImage imageNamed:@"yaoshi"];
            cell.guideLabel.text = @"密码助手";
            cell.isLockImageview.image = [UIImage imageNamed:@"unlock"];
            break;
        case 1:
            cell.guideImageView.image = [UIImage imageNamed:@"jizhangben"];
            cell.guideLabel.text = @"记账本";
            cell.isLockImageview.image = [UIImage imageNamed:@"jiantou"];
            break;
        case 2:
            cell.guideImageView.image = [UIImage imageNamed:@"clearCache"];
            cell.guideLabel.text = @"清除缓存";
            cell.isLockImageview.image = [UIImage imageNamed:@"jiantou"];
            break;
        case 3:
            cell.guideImageView.image = [UIImage imageNamed:@"shezhi"];
            cell.guideLabel.text = @"重置密码";
            cell.isLockImageview.image = [UIImage imageNamed:@"jiantou"];

           
            break;
        case 4:
            cell.guideImageView.image = [UIImage imageNamed:@"yijianfankui"];
            cell.guideLabel.text = @"对我们的意见";
            cell.isLockImageview.image = [UIImage imageNamed:@"jiantou"];
           
            break;
        case 5:
            cell.guideImageView.image = [UIImage imageNamed:@"guanyuwomen"];
            cell.guideLabel.text = @"关于我们";
            cell.isLockImageview.image = [UIImage imageNamed:@"jiantou"];
            break;
            
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    switch (indexPath.row) {
        case 0:
            if(self.isLogin == NO )
            {
                [self alertAction:@"请登录使用" message:@"由于您没有登录,暂时不能使用该功能"];
            }
            else
            {
                AVQuery *query = [AVQuery queryWithClassName:@"securityHelper"];
                [query whereKey:@"phoneNumber" equalTo:[[AVUser currentUser] username]];
                [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
                    if (objects.count <= 0) {
                        self.secrityVC = [[SecurityHelperVC alloc]init];
                        [self.navigationController pushViewController:self.secrityVC animated:YES];
                    }
                    //如果有数据的话需要输入安全密码
                    else
                    {
                        
                        AVQuery *que = [AVQuery queryWithClassName:@"UserClass"];
                        [que whereKey:@"phoneNumber" equalTo:[[AVUser currentUser] username]];
                        [que findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
                            if (objects.count > 0) {
                               AVObject *obj = [AVObject objectWithoutDataWithClassName:@"UserClass" objectId:[objects[0] objectId]];
                                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"请输入安全密码" message:@"请输入您的安全密码" preferredStyle:UIAlertControllerStyleAlert];
                                UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
                                    if ([self.securityPwd isEqualToString:[obj objectForKey:@"securityPwd"]]) {
                                        self.secrityVC = [[SecurityHelperVC alloc]init];
                                        [self.navigationController pushViewController:self.secrityVC animated:YES];
                                    }
                                    else
                                    {
                                        [self alertAction:@"失败" message:@"安全密码输入错误"];
                                    }

                                }];
                                [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
                                    self.securityPwd = textField.text;
                                }];
                            }
                        }];
                    }
                }];
            }
            break;
        case 1:
            if (self.isLogin == NO) {
                [self alertAction:@"请登录使用" message:@"由于您没有登录,暂时不能使用该功能"];
            }
            else
            {
                self.cashbookVC = [[CashbookVC alloc]init];
                [self.navigationController pushViewController:self.cashbookVC animated:YES];
            }
            break;
        case 2:
            
            break;
        case 3:
            if(self.isLogin == NO)
            {
                //没有登录时不能进行重置密码
            }
            else
            {
              
            }
            break;
        case 4:
            break;
        case 5:
         {
            AboutUsViewController *aboutus = [[AboutUsViewController alloc]init];
            [self.navigationController pushViewController:aboutus animated:YES];
         }
        break;
    }

}
-(void)alertAction:(NSString *)alertString message:(NSString *)messagestring
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:alertString message:messagestring preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
           }];
    UIAlertAction *Noaction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        self.myImageView.userInteractionEnabled = NO;
        [self.unLoginButton setTitle:@"未登陆" forState:UIControlStateNormal];
        self.myImageView.image = [UIImage imageNamed:@"default_account_userphoto_default@2x"];
        self.switchAccountButton.hidden = YES;
        self.isLogin = NO;
        
    }];
    [alert addAction:action];
    if (self.isLogin == YES) {
        [alert addAction:Noaction];
        [self presentViewController:alert animated:YES completion:^{
        }];
    }
    else
    {
        [self presentViewController:alert animated:YES completion:^{
        }];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
